<template>
  <el-dialog
    v-model="modalVisible"
    title="编辑文件名称"
    @before-ok="createOk"
    @close="close(createRef)"
    width="500px"
    ><el-form
      class="mt10"
      :model="createForm"
      ref="createRef"
      :rules="createRules"
      label-width="100px"
      size="large"
    >
      <el-form-item label="文件名称：" prop="former_name">
        <el-input v-model="createForm.former_name"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="flex end">
        <el-button @click="modalVisible = false">取消</el-button>
        <el-button type="primary" @click="createOk(createRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts">
export default {
  name: "mateFilesUpdateName",
};
</script>
<script lang="ts" setup>
import { ref, reactive, getCurrentInstance } from "vue";
import type { FormInstance } from "element-plus";
import { Result, ResultError } from "@/types";
import { updateFileName } from "@/api/mate/files";

const {
  proxy: { $message, $utils },
} = getCurrentInstance() as any;

const emit = defineEmits(["success"]);

const modalVisible = ref<boolean>(false);

const createRef = ref<HTMLElement>();

const operation = ref<string>("update");

const operationId = ref<number | string>(0);

const createForm = ref({
  former_name: "",
});
const createRules = reactive({
  former_name: [{ required: true, message: "文件名称不能为空！" }],
});

const createOk = async (formEl: typeof FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid: any, fields: any) => {
    if (valid) {
      updateFileName({
        id: operationId.value,
        former_name: createForm.value.former_name,
      })
        .then((res: Result) => {
          $message.success("保存成功");
          close(formEl);
          emit("success");
        })
        .catch((err: ResultError) => {
          $utils.errorMsg(err);
        });
    }
  });
};
const open = (id = 0, name = "") => {
  operation.value = "update";
  operationId.value = id;
  createForm.value.former_name = name;
  modalVisible.value = true;
};

const close = async (formEl: typeof FormInstance | undefined) => {
  if (formEl) {
    formEl.resetFields();
  }
  operationId.value = 0;
  modalVisible.value = false;
};

defineExpose({ open });
</script>
